<?php

namespace Shahu\Common\common;

use Random\RandomException;

/**
 * 生成默认首字母头像
 */
class DefaultAvatar
{
    /**
     * 首字母头像
     * @param $text
     * @return string
     * @throws RandomException
     */
    public static function letter_avatar($text) : string
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = static::hsv2rgb($hue / random_int(50, 360));
        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" ry="100" width="100" height="100"></rect><text x="50" y="50" font-size="50" fill="' . $color . '" text-anchor="middle" alignment-baseline="central">' . $first . '</text></svg>');
        return 'data:image/svg+xml;base64,' . $src;
    }


    /**
     * 随机底色
     * @param $h
     * @return array
     */
    private static function hsv2rgb($h) : array
    {
        $r = $g = $b = 0;
        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = 0.9 * (1 - 0.3);
        $q = 0.9 * (1 - $f * 0.3);
        $t = 0.9 * (1 - (1 - $f) * 0.3);
        switch ($i % 6) {
            case 0:
                $r = 0.9;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = 0.9;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = 0.9;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = 0.9;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = 0.9;
                break;
            case 5:
                $r = 0.9;
                $g = $p;
                $b = $q;
                break;
        }
        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}